import React, { PureComponent } from 'react';
import { Link, withRouter } from 'react-router-dom';
import axios from 'axios';

import { Form, Icon, Input, Button, Checkbox,message } from 'antd';
import './login.css'
const FormItem = Form.Item;

class NormalLoginForm extends PureComponent {
    handleSubmit = (e) => {
        e.preventDefault();

        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                axios({
                    method:'post',
                    url:"http://localhost:8080/user/login",
                    data:values
                }).then((res)=>{
                    try {
                        const data=res.data.data;
                        const token = data.token;
                        const userType = data.power;
                        window.location.href=('/homepage');
                        sessionStorage.setItem("type",userType)
                        sessionStorage.setItem('token', token);
                    }catch (e) {
                        console.log(e)
                        message.error("登录失败，请检查用户名或密码")
                    }
                });
            }
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <h1>知心网</h1>
            <Form onSubmit={this.handleSubmit} className="login-form">
                <FormItem>
                    {getFieldDecorator('username', {
                        rules: [{ required: true, message: '请输入用户名' }],
                    })(
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />
                    )}
                </FormItem>
                <FormItem>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: '请输入密码' }],
                    })(
                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" />
                    )}
                </FormItem>
                <FormItem>
                    {getFieldDecorator('remember', {
                        valuePropName: 'checked',
                        initialValue: true,
                    })(
                        <Checkbox>记住密码</Checkbox>
                    )}
                    <a className="login-form-forgot" href="">忘记密码</a>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        登录
                    </Button>
                    <Link to="./zhuce">立刻注册！</Link>
                </FormItem>
            </Form>
            </div>
        );
    }
}

const Login = Form.create()(NormalLoginForm);
export default withRouter(Login);